import { Router, Request, Response } from 'express';
import { sqlExecutionEngine } from '../services/SQLExecutionEngine';
import { taskQueueManager } from '../services/TaskQueueManager';
import { executionMonitor } from '../services/ExecutionMonitor';
import { ExecutionService } from '../services/ExecutionService';
import Joi from 'joi';

const router = Router();
const executionService = new ExecutionService();

// 验证中间件
const validateExecuteScript = (req: Request, res: Response, next: any) => {
  const schema = Joi.object({
    script_id: Joi.string().uuid().required(),
    connection_id: Joi.string().uuid().required(),
    priority: Joi.number().integer().min(1).max(10).default(5),
    timeout: Joi.number().integer().min(1000).max(3600000).optional(), // 1秒到1小时
    executed_by: Joi.string().optional()
  });

  const { error, value } = schema.validate(req.body);
  if (error) {
    return res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(d => d.message)
    });
  }

  req.body = value;
  next();
  next();
};

// 提交执行任务
router.post('/', validateExecuteScript, async (req: Request, res: Response) => {
  try {
    const { script_id, connection_id, priority, timeout, executed_by } = req.body;

    // 验证执行权限
    const permission = await executionService.validateExecutionPermission(
      script_id, 
      connection_id, 
      executed_by
    );

    if (!permission.allowed) {
      return res.status(403).json({
        success: false,
        message: permission.reason
      });
    }

    // 提交到执行引擎
    const taskId = await sqlExecutionEngine.submitExecution({
      scriptId: script_id,
      connectionId: connection_id,
      priority,
      timeout,
      executedBy: executed_by
    });

    res.status(202).json({
      success: true,
      message: '执行任务已提交',
      data: {
        task_id: taskId,
        status: 'queued'
      }
    });

  } catch (error: any) {
    console.error('提交执行任务失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '提交执行任务失败'
    });
  }
});

// 取消执行
router.delete('/:executionId', async (req: Request, res: Response) => {
  try {
    const { executionId } = req.params;

    const cancelled = await sqlExecutionEngine.cancelExecution(executionId);

    if (cancelled) {
      res.json({
        success: true,
        message: '执行已取消'
      });
    } else {
      res.status(404).json({
        success: false,
        message: '执行不存在或无法取消'
      });
    }

  } catch (error: any) {
    console.error('取消执行失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '取消执行失败'
    });
  }
});

// 获取执行进度
router.get('/:executionId/progress', async (req: Request, res: Response) => {
  try {
    const { executionId } = req.params;

    const progress = await sqlExecutionEngine.getExecutionProgress(executionId);

    if (progress) {
      res.json({
        success: true,
        data: progress
      });
    } else {
      res.status(404).json({
        success: false,
        message: '执行进度不存在'
      });
    }

  } catch (error: any) {
    console.error('获取执行进度失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取执行进度失败'
    });
  }
});

// 获取执行详情
router.get('/:executionId', async (req: Request, res: Response) => {
  try {
    const { executionId } = req.params;

    const execution = await executionService.getExecution(executionId);

    if (execution) {
      // 获取额外的监控信息
      const [progress, snapshot, alerts] = await Promise.all([
        sqlExecutionEngine.getExecutionProgress(executionId),
        executionMonitor.getExecutionSnapshot(executionId),
        executionMonitor.getExecutionAlerts(executionId)
      ]);

      res.json({
        success: true,
        data: {
          ...execution,
          progress,
          snapshot,
          alerts
        }
      });
    } else {
      res.status(404).json({
        success: false,
        message: '执行记录不存在'
      });
    }

  } catch (error: any) {
    console.error('获取执行详情失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取执行详情失败'
    });
  }
});

// 获取执行历史
router.get('/', async (req: Request, res: Response) => {
  try {
    const {
      script_id,
      connection_id,
      status,
      executed_by,
      start_date,
      end_date,
      page = 1,
      page_size = 20
    } = req.query;

    const limit = Math.min(parseInt(page_size as string) || 20, 100);
    const offset = (parseInt(page as string) - 1 || 0) * limit;

    const options = {
      script_id: script_id as string,
      connection_id: connection_id as string,
      status: status as any,
      executed_by: executed_by as string,
      start_date: start_date ? new Date(start_date as string) : undefined,
      end_date: end_date ? new Date(end_date as string) : undefined,
      limit,
      offset
    };

    const result = await executionService.getExecutionHistory(options);

    res.json({
      success: true,
      data: result
    });

  } catch (error: any) {
    console.error('获取执行历史失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取执行历史失败'
    });
  }
});

// 获取队列状态
router.get('/queue/status', async (req: Request, res: Response) => {
  try {
    const [engineStatus, queueStatus, queueHealth] = await Promise.all([
      sqlExecutionEngine.getQueueStatus(),
      taskQueueManager.getQueueStatus(),
      taskQueueManager.getQueueHealth()
    ]);

    res.json({
      success: true,
      data: {
        engine: engineStatus,
        queue: queueStatus,
        health: queueHealth
      }
    });

  } catch (error: any) {
    console.error('获取队列状态失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取队列状态失败'
    });
  }
});

// 获取执行统计
router.get('/stats/overview', async (req: Request, res: Response) => {
  try {
    const [executionStats, monitoringStats] = await Promise.all([
      sqlExecutionEngine.getExecutionStats(),
      executionMonitor.getMonitoringStats()
    ]);

    res.json({
      success: true,
      data: {
        execution: executionStats,
        monitoring: monitoringStats
      }
    });

  } catch (error: any) {
    console.error('获取执行统计失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取执行统计失败'
    });
  }
});

// 获取运行中的执行
router.get('/running/list', async (req: Request, res: Response) => {
  try {
    const runningExecutions = await executionService.getRunningExecutions();
    
    // 获取每个执行的详细信息
    const detailedExecutions = await Promise.all(
      runningExecutions.map(async (execution) => {
        const [progress, snapshot] = await Promise.all([
          sqlExecutionEngine.getExecutionProgress(execution.id),
          executionMonitor.getExecutionSnapshot(execution.id)
        ]);
        
        return {
          ...execution,
          progress,
          snapshot
        };
      })
    );

    res.json({
      success: true,
      data: detailedExecutions
    });

  } catch (error: any) {
    console.error('获取运行中执行失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取运行中执行失败'
    });
  }
});

// 批量取消执行
router.post('/batch/cancel', async (req: Request, res: Response) => {
  try {
    const schema = Joi.object({
      execution_ids: Joi.array().items(Joi.string().uuid()).min(1).max(50).required()
    });

    const { error, value } = schema.validate(req.body);
    if (error) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: error.details.map(d => d.message)
      });
    }

    const { execution_ids } = value;
    const result = await executionService.cancelRunningExecutions(execution_ids);

    res.json({
      success: true,
      message: `成功取消 ${result.cancelled_count} 个执行`,
      data: result
    });

  } catch (error: any) {
    console.error('批量取消执行失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '批量取消执行失败'
    });
  }
});

// 获取执行告警
router.get('/:executionId/alerts', async (req: Request, res: Response) => {
  try {
    const { executionId } = req.params;
    const alerts = await executionMonitor.getExecutionAlerts(executionId);

    res.json({
      success: true,
      data: alerts
    });

  } catch (error: any) {
    console.error('获取执行告警失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取执行告警失败'
    });
  }
});

// 解决告警
router.post('/alerts/:alertId/resolve', async (req: Request, res: Response) => {
  try {
    const { alertId } = req.params;
    const resolved = await executionMonitor.resolveAlert(alertId);

    if (resolved) {
      res.json({
        success: true,
        message: '告警已解决'
      });
    } else {
      res.status(404).json({
        success: false,
        message: '告警不存在'
      });
    }

  } catch (error: any) {
    console.error('解决告警失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '解决告警失败'
    });
  }
});

// 获取所有告警
router.get('/alerts/list', async (req: Request, res: Response) => {
  try {
    const {
      severity,
      type,
      resolved,
      limit = 50
    } = req.query;

    const options = {
      severity: severity as any,
      type: type as any,
      resolved: resolved === 'true' ? true : resolved === 'false' ? false : undefined,
      limit: Math.min(parseInt(limit as string) || 50, 200)
    };

    const alerts = await executionMonitor.getAllAlerts(options);

    res.json({
      success: true,
      data: alerts
    });

  } catch (error: any) {
    console.error('获取告警列表失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取告警列表失败'
    });
  }
});

// 获取性能历史
router.get('/:executionId/performance', async (req: Request, res: Response) => {
  try {
    const { executionId } = req.params;
    const { minutes = 60 } = req.query;

    const performance = await executionMonitor.getPerformanceHistory(
      executionId, 
      parseInt(minutes as string)
    );

    res.json({
      success: true,
      data: performance
    });

  } catch (error: any) {
    console.error('获取性能历史失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '获取性能历史失败'
    });
  }
});

// 设置执行超时
router.post('/:executionId/timeout', async (req: Request, res: Response) => {
  try {
    const { executionId } = req.params;
    
    const schema = Joi.object({
      timeout_ms: Joi.number().integer().min(1000).max(3600000).required()
    });

    const { error, value } = schema.validate(req.body);
    if (error) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: error.details.map(d => d.message)
      });
    }

    const { timeout_ms } = value;
    await executionMonitor.setExecutionTimeout(executionId, timeout_ms);

    res.json({
      success: true,
      message: '超时设置成功'
    });

  } catch (error: any) {
    console.error('设置执行超时失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '设置执行超时失败'
    });
  }
});

// 清理队列
router.post('/queue/clear', async (req: Request, res: Response) => {
  try {
    await sqlExecutionEngine.clearQueue();

    res.json({
      success: true,
      message: '队列已清空'
    });

  } catch (error: any) {
    console.error('清理队列失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '清理队列失败'
    });
  }
});

// 暂停/恢复队列
router.post('/queue/:action', async (req: Request, res: Response) => {
  try {
    const { action } = req.params;

    if (action === 'pause') {
      sqlExecutionEngine.pauseQueue();
      res.json({
        success: true,
        message: '队列已暂停'
      });
    } else if (action === 'resume') {
      sqlExecutionEngine.resumeQueue();
      res.json({
        success: true,
        message: '队列已恢复'
      });
    } else {
      res.status(400).json({
        success: false,
        message: '无效的操作，只支持 pause 或 resume'
      });
    }

  } catch (error: any) {
    console.error('队列操作失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '队列操作失败'
    });
  }
});

// 设置最大并发数
router.post('/queue/concurrency', async (req: Request, res: Response) => {
  try {
    const schema = Joi.object({
      max_concurrent: Joi.number().integer().min(1).max(20).required()
    });

    const { error, value } = schema.validate(req.body);
    if (error) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: error.details.map(d => d.message)
      });
    }

    const { max_concurrent } = value;
    sqlExecutionEngine.setMaxConcurrentExecutions(max_concurrent);

    res.json({
      success: true,
      message: `最大并发数已设置为 ${max_concurrent}`
    });

  } catch (error: any) {
    console.error('设置并发数失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '设置并发数失败'
    });
  }
});

export default router;